package com.yunshu.yunshuapp.xianhuo;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Layout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.kuaixun.KuaixunSubscribeActivity;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.user.UserInfoActivity;
import com.yunshu.yunshuapp.utils.YSUtils;

import org.w3c.dom.Text;

import java.io.IOException;
import java.text.BreakIterator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;

import static com.igexin.sdk.GTServiceManager.context;

public class AddBaojiaActivity extends AppCompatActivity implements View.OnClickListener,Toolbar.OnMenuItemClickListener,TimePicker.OnTimeChangedListener {

//    private String tempDate = "";
//    private String tempTime = "";
    public TextView timeLabel;
    public EditText baojiaTextView;
    public ImageButton image1;
    public ImageButton image2;
    public ImageButton image3;
    private ImageLoader mImageLoader;
    private String[] imageUrls = new String[3];
    private TextView loadingLabel;
    private Xianhuo model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_baojia);
        NavigationBar bar = (NavigationBar) findViewById(R.id.navigationBar);
        bar.setTitle("添加报价和库存表");
        bar.putInActivity(this);

        String xianhuoString = (String) this.getIntent().getExtras().get("model");
        if (xianhuoString != null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                model = mapper.readValue(xianhuoString, Xianhuo.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        RelativeLayout timeField = (RelativeLayout) findViewById(R.id.timeField);
//        timeField.setOnClickListener(this);

        timeLabel = (TextView) findViewById(R.id.timeValueLabel);
        baojiaTextView = (EditText) findViewById(R.id.editText2);
        image1 = (ImageButton) findViewById(R.id.imageButton1);
        image2 = (ImageButton) findViewById(R.id.imageButton2);
        image3 = (ImageButton) findViewById(R.id.imageButton3);
        loadingLabel = (TextView)findViewById(R.id.loadingLabel);
        image1.setOnClickListener(this);
        image2.setOnClickListener(this);
        image3.setOnClickListener(this);

        // 获取图片加载实例
        mImageLoader = ImageLoader.getInstance();

        for (int i=0 ; i < 3 ; i++ ){
            imageUrls[i] = "";
        }

        Calendar mycalendar=Calendar.getInstance();
        int year = mycalendar.get(Calendar.YEAR); //获取Calendar对象中的年
        int month = mycalendar.get(Calendar.MONTH) + 1;//获取Calendar对象中的月
        int day = mycalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天

        int hour = mycalendar.get(Calendar.HOUR_OF_DAY);
        int minute = mycalendar.get(Calendar.MINUTE);

        timeLabel.setText(year + "-" + month + "-" + day + " " + hour + ":" + minute);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_kuaixun , menu);
        menu.getItem(0).setTitle("确定");
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_subscribeKuaixun:
                this.submit();
                break;
            default:break;
        }
        return true;

    }

    public void submit() {
        String time = this.timeLabel.getText().toString();
        String baojia = time + "发布:" + this.baojiaTextView.getText().toString() + "\n" + model.getAdvert();

        model.setAdvert(baojia);
        String kucunpic = null;
        ArrayList<String> urls = new ArrayList<String>();
        for (int i = 0 ; i < 3 ; i ++ ){
            if( imageUrls[i].length() > 0 ) {
                if (kucunpic == null) {
                    kucunpic = imageUrls[i];
                }else{
                    urls.add(imageUrls[i]);
                }
            }
        }

        if (kucunpic != null){
            model.setKucunpic(kucunpic);
        }

        if (urls.size() > 0) {
            model.setProductpic(urls.get(0));
        }

        if (urls.size() > 1) {
            model.setProductpic(urls.get(1));
        }

        Map<String, String> params = model.serialize();
        new YSRequest(this).POST(YSRequest.XIANHUO_UPDATE, params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                if (isSuccess == YSRequest.REQUEST_OK){
                    runOnUiThread(new Runnable() {      // UI thread
                        @Override
                        public void run() {
                            new AlertDialog.Builder(AddBaojiaActivity.this).setTitle("提示")//设置对话框标题

                                    .setMessage("发布成功！")//设置显示的内容 ;
                                    .setPositiveButton("我知道了",new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                            AddBaojiaActivity.this.finish();
                                        }
                                    }).show();//在按键响应事件中显示此对话框
                        }
                    });
                }
            }
        });
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        this.submit();

        return false;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.timeField) {
            this.chooseTime();
        }else if(view.getId() == R.id.imageButton1) {
            PhotoPicker.builder()
                    .setPhotoCount(1)
                    .setShowCamera(true)
                    .setShowGif(false)
                    .setPreviewEnabled(false)
                    .start(this, PhotoPicker.REQUEST_CODE + 1);
        }else if(view.getId() == R.id.imageButton2) {
            PhotoPicker.builder()
                    .setPhotoCount(1)
                    .setShowCamera(true)
                    .setShowGif(false)
                    .setPreviewEnabled(false)
                    .start(this, PhotoPicker.REQUEST_CODE + 2);
        }else if(view.getId() == R.id.imageButton3) {
            PhotoPicker.builder()
                    .setPhotoCount(1)
                    .setShowCamera(true)
                    .setShowGif(false)
                    .setPreviewEnabled(false)
                    .start(this, PhotoPicker.REQUEST_CODE + 3);
        }
    }

    private void chooseTime(){

        //初始化Calendar日历对象
        Calendar mycalendar=Calendar.getInstance();
        int year = mycalendar.get(Calendar.YEAR); //获取Calendar对象中的年
        int month = mycalendar.get(Calendar.MONTH);//获取Calendar对象中的月
        int day = mycalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天

        //创建DatePickerDialog对象
        DatePickerDialog dpd=new DatePickerDialog(this,Datelistener,year,month,day);
        dpd.show();//显示DatePickerDialog组件
    }

    private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener()
    {

        /**params：view：该事件关联的组件
         * params：myyear：当前选择的年
         * params：monthOfYear：当前选择的月
         * params：dayOfMonth：当前选择的日
         */
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {


            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            int year = myyear;
            int month = monthOfYear;
            int day = dayOfMonth;
            //更新日期
            updateDate(year, month,day);



            AlertDialog.Builder builder2 = new AlertDialog.Builder( AddBaojiaActivity.this );
            builder2.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
//                    if (time.length() > 0) { //清除上次记录的日期
//                        time.delete(0, time.length());
//                    }

//                    timeLabel.setText( tempTime );
                    dialog.dismiss();
                }
            });
            builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            Calendar calendar = Calendar.getInstance();

            int hour = calendar.get(Calendar.HOUR);
            int minute = calendar.get(Calendar.MINUTE);

            AlertDialog dialog2 = builder2.create();
            View dialogView2 = View.inflate(AddBaojiaActivity.this, R.layout.dialog_time, null);
            TimePicker timePicker = (TimePicker) dialogView2.findViewById(R.id.timePicker);
            timePicker.setCurrentHour(hour);
            timePicker.setCurrentMinute(minute);
            timePicker.setIs24HourView(true); //设置24小时制
            timePicker.setOnTimeChangedListener(AddBaojiaActivity.this);
            dialog2.setTitle("设置时间");
            dialog2.setView(dialogView2);
            dialog2.show();

        }

    };

    private void updateDate(int year, int month, int day) {

//        tempDate = year + "-" + month + "-" +day;
//        Calendar calendar = Calendar.getInstance();
//
//        int hour = calendar.get(Calendar.HOUR);
//        int minute = calendar.get(Calendar.MINUTE);
//        tempTime = tempDate + " " + String.valueOf(hour) + ":" + String.valueOf(minute);

    }

    @Override
    public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
//        tempTime = tempDate + " " + String.valueOf(hour) + ":" + String.valueOf(minute);

    }


    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK
                && requestCode >= PhotoPicker.REQUEST_CODE
                && requestCode <= PhotoPicker.REQUEST_CODE +3) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                String photoPath = photos.get(0);
                this.uploadImage(photoPath , requestCode - PhotoPicker.REQUEST_CODE);
            }
        }
    }

    private void uploadImage(String photoPath, final int imgCode ) {

        Bitmap img = BitmapFactory.decodeFile(photoPath);
        Bitmap newimg = null;
        float w = img.getWidth();
        float h = img.getHeight();
        if (w <= 900 || h <= 1200){
            newimg = img;
        }else if( w/h < 0.75 ){
            newimg = Bitmap.createScaledBitmap(img, (int)(1200 * w/h), 1200, true);
        }else {
            newimg = Bitmap.createScaledBitmap(img, 900, (int)(900*h/w), true);
        }

        this.setImageLoading(imgCode);

        new YSRequest(this).uploadImg2(photoPath,newimg, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode json) {
//                {"code":1,"result":"{\"img\":\"http://60.205.225.113/pictureService/showImage.action?type=0&filename=5a0313c5-9f3e-4788-8e25-c7d60f3e9fda.png\"}","msg":"上传成功"}
                ObjectMapper mapper = new ObjectMapper();
                try {
                    JsonNode resultNode = mapper.readTree(json.textValue());
                    JsonNode imgNode = resultNode.get("img");
                    if (imgNode != null){

                        String avatarUrl = imgNode.asText();
                        updateImage(avatarUrl,imgCode);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    hideImageLoading(imgCode);
                }
            }
        });
    }

    private void setImageLoading(int imgCode) {
        loadingLabel.setText("图片上传中...");
        loadingLabel.setVisibility(View.VISIBLE);
    }

    private void hideImageLoading(int imgCode) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadingLabel.setText("图片上传完毕！");
                loadingLabel.setVisibility(View.VISIBLE);
            }
        });

    }

    private void updateImage(final String avatarUrl, final int imgCode) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ImageView imgView = null;
                imageUrls[imgCode - 1] = avatarUrl;
                if(imgCode == 1){
                    imgView = (ImageView) findViewById(R.id.imageButton1);
                }else if (imgCode == 2){
                    imgView = (ImageView) findViewById(R.id.imageButton2);
                }else if (imgCode == 3){
                    imgView = (ImageView) findViewById(R.id.imageButton3);
                }
                mImageLoader.displayImage(avatarUrl, imgView);
            }
        });
    }
}
